
function number2spacing(num) {
    let returnstr = ``
    for (let i = 0; i < num; i++) {
        returnstr = returnstr + '    '
    }
    return returnstr
}
function node2code(node, num) {
    let spacing = number2spacing(num)
    if (node.isGroup) {
        let children = ``
        if (node.children.length) {
            for (let i = 0; i < node.children.length; i++) {
                children = children + node2code(node.children[i], num + 1)
            }
        }
        let returnstr =
            `
${spacing}<TresGroup${node.name && ' name="' + node.name + '"'} :position="[${node.position.x}, ${node.position.y}, ${node.position.z}]" :scale="[${node.scale.x}, ${node.scale.y}, ${node.scale.z}]" :rotation="[${node.rotation.x}, ${node.rotation.y}, ${node.rotation.z}]" :visible="${node.visible}" >${children}
${spacing}</TresGroup>`
        return returnstr
    }
    if (node.isMesh) {
        let returnstr =
            `
${spacing}<TresMesh${node.name && ' name="' + node.name + '"'} :geometry="nodes['${node.name}'].geometry" :material="materials['${node.material.name}']" :position="[${node.position.x}, ${node.position.y}, ${node.position.z}]" :scale="[${node.scale.x}, ${node.scale.y}, ${node.scale.z}]" :rotation="[${node.rotation.x}, ${node.rotation.y}, ${node.rotation.z}]" :visible="${node.visible}" >
${spacing}</TresMesh>`
        return returnstr
    }

    return ''
}

export function model2code(scene, address) {
    console.log('scene', scene);
    const now = new Date();
    const year = now.getFullYear(); // 年
    const month = now.getMonth() + 1; // 月（注意：月份从 0 开始，所以需要 +1）
    const day = now.getDate(); // 日
    const hour = now.getHours(); // 时
    const minute = now.getMinutes(); // 分
    const second = now.getSeconds(); // 秒
    const returnstr = `<!--
 * @Author: 郭文军的glb2tresjs组件生成器
 * @FileAddress: ${address}
 * @Date: ${year}-${month}-${day} ${hour}:${minute}:${second}
-->
<template>
    <TresGroup ref="group" :position="[0, 0, 0]">
${node2code(scene, 2)}
    </TresGroup>
</template>

<script setup>
import { useGLTF } from '@tresjs/cientos'
import { shallowRef } from 'vue';
import { AnimationMixer } from 'three';
import { useLoop } from '@tresjs/core'

const { onBeforeRender } = useLoop()
const group = shallowRef(null)
const { nodes, materials, animations } = await useGLTF('${address}', { draco: true, decoderPath: '/draco/' })
let actions = [];
let mixers = [];
watch(group, () => {
    animations.forEach(element => {
        const mixer = new AnimationMixer(group.value)
        mixers.push(mixer)
        actions.push(mixer.clipAction(element))
    });
    onBeforeRender(({ delta }) => {
        mixers.forEach(mixer => {
            if (mixer) mixer.update(delta);
        })
    })
    actions.forEach(action => {
        action.play()
    })
})
</script>`
    return returnstr
}